package com.atguigu.gmall.mq.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author mqx
 * @date 2020-10-23 14:07:16
 */
@RestController
@RequestMapping("/mq")
public class MqController {

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //  配置一个映射路径，发送消息
    @RequestMapping("sendConfirm")
    public Result sendConfirm(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //  必然调用工具类发送消息
        rabbitService.sendMessage("exchange.confirm","routing.confirm",simpleDateFormat.format(new Date()));
        return Result.ok();
    }

    @GetMapping("sendDeadLettle")
    public Result sendDeadLettle(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //  发送消息
        rabbitService.sendMessage(DeadLetterMqConfig.exchange_dead,DeadLetterMqConfig.routing_dead_1,"hello word!");

        //  消息什么时候发送的！
        System.out.println(sdf.format(new Date())+"发送了消息。。。。。");
        return Result.ok();
    }

    @GetMapping("sendDelay")
    public Result sendDelay(){
        //  发送消息！
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //  让交换机变成死信交换机，则必须满足三种情况之一，满足ttl 。
//        rabbitTemplate.convertAndSend(DelayedMqConfig.exchange_delay, DelayedMqConfig.routing_delay, "OK",
//                new MessagePostProcessor() {
//                    @Override
//                    public Message postProcessMessage(Message message) throws AmqpException {
//                        //  在此设置消息的ttl
//                        message.getMessageProperties().setDelay(10 * 1000);
//                        //  打印消息发送了。
//                        System.out.println(sdf.format(new Date())+"发送了消息。。。。。");
//                        return message;
//                    }
//                });
        //  调用工具类
        rabbitService.sendDelayMessage(DelayedMqConfig.exchange_delay, DelayedMqConfig.routing_delay, "OK",10);
        return Result.ok();
    }
}
